<?php

namespace App\Http\Controllers\Admin;

use App\AdminModel\Archive;
use App\AdminModel\Arctype;
use App\AdminModel\AdminRole;
use App\AdminModel\Admin;
use App\Http\Requests\CreateArticleRequest;
use App\Http\Requests\CreateLink2Request;
use App\Helpers\UploadImages;
use App\Http\Requests\ImagesUploadRequest;
use App\Notifications\ArticlePublishedNofication;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Log;

class ArticleController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth.admin:admin');
    }

       /**导入关键词
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */

    function KeywordsCreate()
    {
        return view('admin.keywords.create');
    }   
    //关键词列表
    function Keywords()
    {
        $adminRole=AdminRole::where('role_id',3)->get();
        $admins=Admin::where('status',1)->where('type',3)->get();
        if(auth('admin')->user()->type!=3)
            $articleList = Archive::where('ismake',0)->orderBy('id','desc')->paginate(30);
        else
            $articleList = Archive::where('ismake',0)->where('dutyadmin',auth('admin')->user()->id)->orderBy('id','desc')->paginate(30);


        return view('admin.keywords.index',compact('articleList','adminRole','admins'));
    }

    function PostKeywordsCreate(Request $request)
    {
           $request['typeid'] = Input::get("typeid");
           $titlearr = Input::get("title");
           $arr1 = explode("\r\n",$titlearr);
            $request['editor'] = auth('admin')->user()->id;
            $request['ismake'] = 0;
            $request['write'] = auth('admin')->user()->name;
            $request['brandid'] = 0;

           foreach ($arr1 as $key => $value) {
              $request['click'] = rand(100,900);
                if(Archive::where('title',$value)->where('created_at','>',Carbon::today())->value('id'))
                {
                   
                }else{
                    $request['keywords'] = $request['title'] = $value;
                   
                    Archive::create($request->all());
                }
           }

            return redirect(action('Admin\ArticleController@Keywords'))->with('success','导入关键词成功');
        
    }





    /**文档创建提交数据处理
     * @param CreateArticleRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    function PostCreate(CreateArticleRequest $request)
    {   
       
      // dd(auth('admin')->user()->id);
        $request['editor'] = auth('admin')->user()->id;


        if(isset($request['flags']))
        {
            $request['flags']=UploadImages::Flags($request['flags']);
        }else{
            $request['flags']='';
        }
        $request['body'] = $this->conImg($request['body'],1);
        if($request['image'])
        {
            $request['litpic']=UploadImages::UploadImage($request);
            if(empty($request['flags']))
            {
                $request['flags'].='p';
            }else{
                $request['flags'].=',p';
            }
        }elseif (preg_match('/<[img|IMG].*?src=[\' | \"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/i',$request['body'],$match)){
            if($request['ycimage'])//远程缩略图
                $request['litpic'] = $this->sltImg($request['ycimage'],1);
            else
              $request['litpic']=$match[1];    
            
            if(empty($request['flags']))
                {
                    $request['flags'].='p';
                }else{
                    $request['flags'].=',p';
                }  
            
        }else{

            if($request['ycimage'])
                $request['litpic'] = $this->sltImg($request['ycimage'],1);
            else
                $request['litpic']='';
        }
       
        if($request['ycimagepics'])
        {
            $ycimagepics = $this->sltImg($request['ycimagepics'],3);
            if($request['imagepics'])
                $request['imagepics'] = $request['imagepics'].$ycimagepics;
            else
                $request['imagepics'] = $ycimagepics;

        }
 // dd($request['imagepics']);
       $request['keywords']=$request['keywords']?$request['keywords']:$request['title'];
        $request['click']=rand(100,900);
        $request['description']=(!empty($request['description']))?str_limit($request['description'],180,''):str_limit(str_replace(['&nbsp;',' ','　',PHP_EOL,'\t'],'',strip_tags(htmlspecialchars_decode($request['body']))), $limit = 180, $end = '');
        $request['write']=auth('admin')->user()->name;
        $request['dutyadmin']=auth('admin')->id();
        //图片alt信息及title替换
        //$request['body']=str_replace(['&nbsp;'],'',$this->ImageInformation($request->input('body'),$request->input('shorttitle')?$request->input('shorttitle'):$request->input('brandname'),$request->input('title')));
        $token=config('app.api', '');
        $mip_api=config('app.mip_api', '');
        $mip_history=config('app.mip_history', '');

        
        //dd($request['body']);
       

       // dd($request['body']);
        //不同文档类型分类入库
        if ($request->input('mid')==0)
        {
           // dd($request->all());
            //重复文档监测
            if(Archive::where('title',$request['title'])->where('created_at','>',Carbon::today())->value('id'))
            {
                exit('标题重复，禁止发布');
            }
            $request['brandid']= !empty($request['bdname'])?Brandarticle::where('brandname','like','%'.$request['bdname'].'%')->value('id'):0;
            $request['brandid']=!empty($request['brandid'])?$request['brandid']:0;
            Archive::create($request->all());

            auth('admin')->user()->notify(new ArticlePublishedNofication(Archive::latest() ->first()));
           
            return redirect('admin.article.article'.$request['hdid']);

        }
        



    }

    function sltImg($str,$cz=1)
    {
        $save_path = $_SERVER ['DOCUMENT_ROOT'] . '/images/thread/';
        // 文件保存目录URL
        $save_url = '/images/thread/';
        $save_path = realpath ( $save_path ) . '/';
        // 图片存储目录
        $imgPath = $save_path . date ( "Y" ). "/". date ( "m" ). '/'. date ( "d" );
        $imgUrl = $save_url . date ( "Y" ). '/'. date ( "m" ). '/'. date ( "d" );
        // 创建文件夹
        // if (! is_dir ( $imgPath )) {
        //     @mkdir ( $imgPath, 0777 );
        // }
        if (!file_exists($imgPath)){
            mkdir($imgPath,0777,true);
        }
        $img_array = array();
        if($cz==3)
            $img_array = explode("\n",$str);
        if($cz==1)
            $img_array = array ($str);
        
        $count = count($img_array)-1;
        // 时间无限制
        set_time_limit ( 0 );
        $fileurl ='';
        foreach ( $img_array as $key => $value ) {
            if($cz ==1 || $cz ==3){
                if(strstr($value,'storage/uploads')===false){
                    $img = trim($value);
                  
                    $imgname = date ( "YmdHis" ) . '_' . rand ( 10000, 99999 ) . ".jpg" ;
                    // 保存到本地的实际文件地址（包含路径和名称）
                    $fileName = $imgPath . '/' . $imgname;
                    // 实际访问的地址
                   
                    if($cz==3 && $count>0){
                       
                            $fileurl .= $imgUrl . "/" . $imgname.',';
                    }
                    if($cz==3 && $count==0)
                        $fileurl .= $imgUrl . "/" . $imgname.',';
                     if($cz==1)
                            $fileurl = $imgUrl . "/" . $imgname;
                    
                   //  // 文件写入
                    ob_start();//打开输出
                    
                    readfile($img);//输出图片文件
                    $img = ob_get_contents();//得到浏览器输出
                    ob_end_clean();//清除输出并关闭
                    $size = strlen($img);//得到图片大小
                    $fp2 = @fopen($fileName, "a");
                    fwrite($fp2, $img);//向当前目录写入图片文件，并重新命名
                    fclose($fp2);
                    
                }
            }else{
                if(strstr($value,'storage/uploads')===false){
                    if(strstr($value,'/images/thread') ===false){

                        $img = trim($value);
                        
                        $imgname = date ( "YmdHis" ) . '_' . rand ( 10000, 99999 ) . ".jpg" ;
                        // 保存到本地的实际文件地址（包含路径和名称）
                        $fileName = $imgPath . '/' . $imgname;
                       //  // 实际访问的地址
                        $fileurl = '"'.$imgUrl . "/" . $imgname.'"';
                        
                       //  // 文件写入
                        ob_start();//打开输出
                        readfile($img);//输出图片文件
                        $img = ob_get_contents();//得到浏览器输出
                        ob_end_clean();//清除输出并关闭
                        $size = strlen($_SERVER ['DOCUMENT_ROOT'].$img);//得到图片大小
                        $fp2 = @fopen($fileName, "a");
                        fwrite($fp2, $img);//向当前目录写入图片文件，并重新命名
                        fclose($fp2);
                    }
                }
            }
            
            
        }

        return  $fileurl;
 
    }

    //文章内远程图片本地化
    function conImg($content,$cz=1)
    {
        $save_path = $_SERVER ['DOCUMENT_ROOT'] . '/images/thread/';
        // 文件保存目录URL
        $save_url = '/images/thread/';
        $save_path = realpath ( $save_path ) . '/';
        // 图片存储目录
        $imgPath = $save_path . date ( "Y" ). "/". date ( "m" ). '/'. date ( "d" );
        $imgUrl = $save_url . date ( "Y" ). '/'. date ( "m" ). '/'. date ( "d" );
        // dd($imgUrl);
        // 创建文件夹
        // if (! is_dir ( $imgPath )) {
        //     @mkdir ( $imgPath, 0777 );
        // }

        if (!file_exists($imgPath)){
            mkdir($imgPath,0777,true);
        }
      
        $content = stripslashes ( $content );
        $img_array = array ();
        // 匹配所有远程图片
        preg_match_all ("/<img([^>]*)\ssrc=([^\s>]+)/", $content, $img_array );
        // 匹配出来的不重复图片
        $img_array = array_unique ( $img_array [2] );
      //  print_r($img_array);
        
        // 时间无限制
        set_time_limit ( 0 );
        foreach ( $img_array as $key => $value ) {
            if($cz ==1){
                if(strstr($value,'storage/uploads')===false){
                    $img = str_replace('"','',$value);
                    if(substr($img, -1)=='/')
                             $img = substr($img, 0,strlen($img)-1);
                    $imgname = date ( "YmdHis" ) . '_' . rand ( 10000, 99999 ) . ".jpg" ;
                    // 保存到本地的实际文件地址（包含路径和名称）
                    $fileName = $imgPath . '/' . $imgname;
                   //  // 实际访问的地址
                    $fileurl = '"'.$imgUrl . "/" . $imgname.'"';
                    
                   //  // 文件写入
                    ob_start();//打开输出
                    if(strstr($img,'http://') || strstr($img,'https://'))
                         readfile($img);//输出图片文件
                    else
                        readfile($_SERVER ['DOCUMENT_ROOT'].$img);//输出图片文件
                    $img = ob_get_contents();//得到浏览器输出
                    ob_end_clean();//清除输出并关闭
                    if(strstr($img,'http://') || strstr($img,'https://'))
                         $size = strlen($img);//得到图片大小
                    else
                            $size = strlen($_SERVER ['DOCUMENT_ROOT'].$img);//得到图片大小
                   
                    $fp2 = @fopen($fileName, "a");
                    fwrite($fp2, $img);//向当前目录写入图片文件，并重新命名
                    fclose($fp2);
                    
                    // 替换原来的图片地址
                    $content = str_replace ( $value, $fileurl, $content );
                }
            }else{
                if(strstr($value,'storage/uploads')===false){
                    if(strstr($value,'/images/thread') ===false){

                        //dd($value);
                        $img = str_replace('"','',$value);
                       
                        if(substr($img, -1)=='/')
                             $img = substr($img, 0,strlen($img)-1);
                        
                        $imgname = date ( "YmdHis" ) . '_' . rand ( 10000, 99999 ) . ".jpg" ;
                        // 保存到本地的实际文件地址（包含路径和名称）
                        $fileName = $imgPath . '/' . $imgname;
                       //  // 实际访问的地址
                        $fileurl = '"'.$imgUrl . "/" . $imgname.'"';
                        
                       //  // 文件写入
                        ob_start();//打开输出
                        if(strstr($img,'http://') || strstr($img,'https://'))
                             readfile($img);//输出图片文件
                        else
                            readfile($_SERVER ['DOCUMENT_ROOT'].$img);//输出图片文件
                        $img = ob_get_contents();//得到浏览器输出
                        ob_end_clean();//清除输出并关闭
                       
                         if(strstr($img,'http://') || strstr($img,'https://'))
                             $size = strlen($img);//得到图片大小
                        else
                                $size = strlen($_SERVER ['DOCUMENT_ROOT'].$img);//得到图片大小
                        $fp2 = @fopen($fileName, "a");
                        fwrite($fp2, $img);//向当前目录写入图片文件，并重新命名
                        fclose($fp2);
                        // 替换原来的图片地址
                      
                        $content = str_replace ( $value, $fileurl, $content );
                    }
                }
            }
            
            
        }
        return  $content;
 
    }

    /**普通文档文档编辑
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    function KeywordsEdit($id)
    {
        $allnavinfos=Arctype::where('mid',0)->pluck('typename','id');
        $pics=explode(',',Archive::where('id',$id)->value('imagepics'));
   
        $articleinfos=Archive::where('ismake',0)->find($id);
        // $articleinfos=DB::table('archives')->join('addonarticles','archives.id','=','addonarticles.id')->where('addonarticles.id','=',$id)->first();
        return view('admin.keywords.article_edit',compact('id','articleinfos','allnavinfos','pics'));
    }
//预览
    function KeywordsShow($id)
    {
        $articleinfos=Archive::find($id);
        return view('admin.keywords.article_show',compact('id','articleinfos'));
    }

    function KeywordsPost(Request $request,$id)
    {
//dd($request['status']);
        if(isset($request['flags']))
        {
            $request['flags']=UploadImages::Flags($request['flags']);
        }else{
            $request['flags']='';
        }
        if($request['image'])
        {

            $request['litpic']=UploadImages::UploadImage($request);
            if(empty($request['flags'])){
                $request['flags'].='p';
            }else{
                $request['flags'].=',p';
            }
        }elseif (isset($request['litpic']) && !empty($request['litpic']))
        {
            if($request['ycimage'])
                $request['litpic'] = $this->sltImg($request['ycimage'],1);
            else
                $request['litpic']=$request['litpic'];

        }elseif (preg_match('/<[img|IMG].*?src=[\' | \"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/i',$request['body'],$match)){
           
            if($request['ycimage'])//远程缩略图
                $request['litpic'] = $this->sltImg($request['ycimage'],1);
            else
                $request['litpic']=$match[1];    
            if(empty($request['flags']))
            {
                $request['flags'].='p';
            }else{
                $request['flags'].=',p';
            }

        }else{
            
            if($request['ycimage'])
                $request['litpic'] = $this->sltImg($request['ycimage'],1);
            else
            $request['litpic']='';
        }

       //  $request['editor'] = auth('admin')->user()->id;
        
        $request['description']=(!empty($request['description']))?str_limit($request['description'],180,''):str_limit(str_replace(['&nbsp;',' ','　',PHP_EOL],'',strip_tags(htmlspecialchars_decode($request['body']))), $limit = 180, $end = '');


            $request['body'] = $this->conImg($request['body'],2);
        
            $request['brandid']=0;
           
           // $request['status']=0;
//dd($request->all());
            Archive::findOrFail($id)->update($request->all());
           
            return redirect('admin/article/keywords')->with('success','修改成功');

    }


    /**普通文档文档编辑
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    function Edit($id)
    {
        $allnavinfos=Arctype::where('mid',0)->pluck('typename','id');
        $pics=explode(',',Archive::where('id',$id)->value('imagepics'));
   
        $articleinfos=Archive::find($id);
        // $articleinfos=DB::table('archives')->join('addonarticles','archives.id','=','addonarticles.id')->where('addonarticles.id','=',$id)->first();
        return view('admin.article.article_edit',compact('id','articleinfos','allnavinfos','pics'));
    }




    /**文档编辑提交处理
     * @param CreateArticleRequest $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    function PostEdit(CreateArticleRequest $request,$id)
    {


        if(isset($request['flags']))
        {
            $request['flags']=UploadImages::Flags($request['flags']);
        }else{
            $request['flags']='';
        }
        if($request['image'])
        {

            $request['litpic']=UploadImages::UploadImage($request);
            if(empty($request['flags'])){
                $request['flags'].='p';
            }else{
                $request['flags'].=',p';
            }
        }elseif (isset($request['litpic']) && !empty($request['litpic']))
        {
            if($request['ycimage'])
                $request['litpic'] = $this->sltImg($request['ycimage'],1);
            else
                $request['litpic']=$request['litpic'];

        }elseif (preg_match('/<[img|IMG].*?src=[\' | \"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/i',$request['body'],$match)){
           
            if($request['ycimage'])//远程缩略图
                $request['litpic'] = $this->sltImg($request['ycimage'],1);
            else
                $request['litpic']=$match[1];    
            if(empty($request['flags']))
            {
                $request['flags'].='p';
            }else{
                $request['flags'].=',p';
            }

        }else{
            
            if($request['ycimage'])
                $request['litpic'] = $this->sltImg($request['ycimage'],1);
            else
            $request['litpic']='';
        }

         $request['editor'] = auth('admin')->user()->id;
        //$request['description']=(!empty($request['description']))?$request['description']:str_limit(mb_ereg_replace('^(　| )+','', preg_replace('/\r|\n/', '', trim(strip_tags(htmlspecialchars_decode($request['body']))))), $limit = 180, $end = '');
        //dd($request->all());
        //$request['description']=str_limit(str_replace(' ','',str_replace('&nbsp;','',mb_ereg_replace('^(　| )+','', preg_replace('/\r|\n/', '', trim(strip_tags(htmlspecialchars_decode($request['description']))))))), $limit = 180, $end = '');
        $request['description']=(!empty($request['description']))?str_limit($request['description'],180,''):str_limit(str_replace(['&nbsp;',' ','　',PHP_EOL],'',strip_tags(htmlspecialchars_decode($request['body']))), $limit = 180, $end = '');


        if (empty($request['imagepics']))
        {
            $request['imagepics']=' ';
        }
        if($request['ycimagepics'])
        {
            $ycimagepics = $this->sltImg($request['ycimagepics'],3);
            if($request['imagepics'])
                $request['imagepics'] = $request['imagepics'].$ycimagepics;
            else
                $request['imagepics'] = $ycimagepics;

        }
        

//dd($this->ImageInformation($request->input('body')));
        //$request['body']=str_replace(['&nbsp;'],'',$this->ImageInformation($request->input('body'),$request->input('shorttitle')?$request->input('shorttitle'):$request->input('brandname'),$request->input('title')));
        //$flags=array_unique(explode(',',Archive::where('id',$id)->value('flags')));
        //$request['flags']=implode(',',$flags);
        $request['body'] = $this->conImg($request['body'],2);
        if ($request->input('mid')==0)
        {

            $request['brandid']= !empty($request['bdname'])?Brandarticle::where('brandname','like','%'.$request['bdname'].'%')->value('id'):0;
            $request['brandid']=!empty($request['brandid'])?$request['brandid']:0;
           
            Archive::findOrFail($id)->update($request->all());
           
             return redirect('admin/article'.$request['hdid']);
            
           
            
        }
            

    }






    function KeywordsDelete($id)
    {
       Archive::where('id',$id)->delete();
       return redirect(action('Admin\ArticleController@Keywords'))->with('success', '删除成功');
   }
   /**等待审核的文档
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    function KeywordsFenpei()
    {

        $idarr = Input::get("idarr");
        $dutyadmin = Input::get("adminid");
        $fptitle = '';
        if($idarr!=''){
            $sh = Input::get("submit");
            foreach ($idarr as $v){
                if($sh=='分配数据'){
                    $confirmId = Archive::where('dutyadmin','!=',0)->where('id',$v)->value('id');
                // dd($confirmtitle);
                    if($confirmId==''){
                        Archive::where('id',$v)->update(['dutyadmin' => $dutyadmin,'status'=>1]);
                    }
                    else    
                         $fptitle .= 'ID：'.$confirmId.'已分配 | ';
                }
            }
        }
       // dd($fptitle);
        if($fptitle != '')
            return redirect(action('Admin\ArticleController@Keywords'))->with('error',$fptitle);
        else    
            return redirect(action('Admin\ArticleController@Keywords'))->with('success','关键词分配成功');
    }



    /**图集上传处理
     * @param ImagesUploadRequest $request
     */
    function UploadImages(ImagesUploadRequest $request){
        UploadImages::UploadImage($request);
    }


    /**文章图片信息修改
     * @param $content
     * @param $title
     * @param $fulltitle
     * @return mixed
     */
    function ImageInformation($content,$title,$fulltitle)
    {
        preg_match('/<img.+(title=\".*?\").+>/i',$content,$match);
        if (empty($match))
        {
            return $content;
        }
        preg_match('/<img.+(alt=\".*?\").+>/i',$content,$match2);
        //dd($match2);
        if (empty($match2))
        {
            return $content;
        }

        $patterns=array();
        $replacement=array();
        $patterns[0]=$match[1];
        $patterns[1]=$match2[1];
        $title=empty($title)?$fulltitle:$title;
        $replacement[0]='title="'.$title.'"';
        $replacement[1]='alt="'.$title.'"';
        //dd($patterns[0]);
        $content=str_replace($patterns[0],$replacement[0],$content);
        $content=str_replace($patterns[1],$replacement[1],$content);
        return $content;
    }


    /**重复标题检测
     * @param Request $request
     * @return int
     */
    public function ArticletitleCheck(Request $request)
    {
        $title=Archive::where('title',$request->input('title'))->count();
        if (!$title)
        {
            $title=Brandarticle::where('title',$request->input('title'))->value('title');
            if (!$title)
            {
                $title=Production::where('title',$request->input('title'))->value('title');
            }
        }
        return $title?1:0;
    }

      

}
